#include "extractpage.h"
#include "ui_extractpage.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QTextStream>
#include <QMimeDatabase>
#include <QListView>
#include "../core/codeprocessor.h"
#include "../core/wordexporter.h"
#include <QApplication>
#include <functional>
#include <QThread>
#include "../core/extractworker.h"

ExtractPage::ExtractPage(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ExtractPage)
    , fileModel(new QFileSystemModel(this))
    , proxyModel(new CustomProxyModel(this))
    , workerThread(new QThread(this))
    , worker(new ExtractWorker)
{
    ui->setupUi(this);
    setupUI();
    createConnections();
    
    // 初始隐藏进度条和标签
    ui->progressBar->hide();
    ui->progressLabel->hide();
    
    // 设置工作线程
    worker->moveToThread(workerThread);
    connect(workerThread, &QThread::finished, worker, &QObject::deleteLater);
    connect(worker, &ExtractWorker::progressChanged, this, [this](int value, const QString &fileName) {
        ui->progressBar->setValue(value);
        ui->progressLabel->setText(tr("正在处理: %1").arg(fileName));
    });
    connect(worker, &ExtractWorker::totalFilesChanged, this, [this](int total) {
        ui->progressBar->setRange(0, total);
    });
    connect(worker, &ExtractWorker::finished, this, [this](bool success) {
        ui->progressBar->hide();
        ui->progressLabel->hide();
        
        if (success) {
            QMessageBox::information(this, tr("成功"), tr("代码已成功导出到Word文档"));
        } else {
            QMessageBox::critical(this, tr("错误"), tr("导出Word文档失败"));
        }
        
        workerThread->quit();
        ui->extractButton->setEnabled(true);
    });
    connect(worker, &ExtractWorker::error, this, [this](const QString &message) {
        ui->progressBar->hide();
        ui->progressLabel->hide();
        QMessageBox::warning(this, tr("警告"), message);
        workerThread->quit();
        ui->extractButton->setEnabled(true);
    });
    
    workerThread->start();
}

ExtractPage::~ExtractPage()
{
    workerThread->quit();
    workerThread->wait();
    delete ui;
}

void ExtractPage::setupUI()
{
    // 设置文件系统模型
    fileModel->setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
    proxyModel->setSourceModel(fileModel);
    ui->fileTreeView->setModel(proxyModel);
    
    // 隐藏不需要的列
    ui->fileTreeView->hideColumn(1); // 隐藏大小列
    ui->fileTreeView->hideColumn(2); // 隐藏类型列
    ui->fileTreeView->hideColumn(3); // 隐藏修改时间列
    
    // 设置语言选择框
    ui->languageComboBox->clear();
    ui->languageComboBox->addItem("全部");
    ui->languageComboBox->addItems(CodeProcessor::getSupportedLanguages());
    
    // 设置语言选择框为可多选，并禁用弹出式菜单的自动隐藏
    QListView *languageView = new QListView(ui->languageComboBox);
    languageView->setSelectionMode(QAbstractItemView::MultiSelection);
    ui->languageComboBox->setView(languageView);
    ui->languageComboBox->setMaxVisibleItems(10);
    
    // 初始化代理模型的过滤器
    proxyModel->setFilterKeyColumn(0);
    proxyModel->setDynamicSortFilter(false);  // 禁用动态过滤，减少闪烁
}

void ExtractPage::createConnections()
{
    connect(ui->browseButton, &QPushButton::clicked, this, &ExtractPage::onBrowseButtonClicked);
    connect(ui->fileTreeView->selectionModel(), &QItemSelectionModel::currentChanged,
            this, &ExtractPage::onFileSelected);
            
    // 使用新的连接方式
    connect(ui->languageComboBox->view()->selectionModel(), 
            &QItemSelectionModel::selectionChanged,
            this, &ExtractPage::onLanguageSelectionChanged);
            
    connect(ui->sizeComboBox, &QComboBox::currentTextChanged,
            this, &ExtractPage::onSizeFilterChanged);
    connect(ui->extractButton, &QPushButton::clicked,
            this, &ExtractPage::onExtractButtonClicked);
}

void ExtractPage::onBrowseButtonClicked()
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("选择项目目录"),
                                                  QString(),
                                                  QFileDialog::ShowDirsOnly
                                                  | QFileDialog::DontResolveSymlinks);
    if (!dir.isEmpty()) {
        ui->pathLineEdit->setText(dir);
        fileModel->setRootPath(dir);
        ui->fileTreeView->setRootIndex(proxyModel->mapFromSource(
            fileModel->index(dir)));
    }
}

void ExtractPage::onFileSelected(const QModelIndex &index)
{
    QModelIndex sourceIndex = proxyModel->mapToSource(index);
    QString filePath = fileModel->filePath(sourceIndex);
    loadFile(filePath);
}

void ExtractPage::loadFile(const QString &filePath)
{
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return;
    }
    
    QTextStream in(&file);
    // 设置文本流的编码为 UTF-8
    in.setCodec("UTF-8");
    ui->previewTextEdit->setText(in.readAll());
}

void ExtractPage::onSizeFilterChanged(const QString &sizeRange)
{
    // 更新代理模型的过滤器
    proxyModel->setSizeFilter(sizeRange);
}

int ExtractPage::countFiles(const QString &path, const QString &language)
{
    QStringList languages;
    if (!language.isEmpty() && language != "全部") {
        languages << language;
    }
    
    int count = 0;
    QFileInfo fileInfo(path);
    
    if (fileInfo.isFile()) {
        if (CodeProcessor::isSourceFile(path, languages)) {
            count++;
        }
    } else if (fileInfo.isDir()) {
        QDir dir(path);
        QFileInfoList entries = dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
        for (const QFileInfo &entry : entries) {
            count += countFiles(entry.filePath(), language);
        }
    }
    
    return count;
}

QStringList ExtractPage::getSelectedLanguages() const
{
    QStringList selectedLanguages;
    QItemSelectionModel *selectionModel = ui->languageComboBox->view()->selectionModel();
    
    // 检查是否选择了"全部"
    if (selectionModel->isSelected(ui->languageComboBox->model()->index(0, 0))) {
        selectedLanguages << "全部";
        return selectedLanguages;
    }
    
    // 获取所有选中的语言
    QModelIndexList selectedIndexes = selectionModel->selectedIndexes();
    for (const QModelIndex &index : selectedIndexes) {
        selectedLanguages << ui->languageComboBox->itemText(index.row());
    }
    
    return selectedLanguages;
}

void ExtractPage::onExtractButtonClicked()
{
    QString currentPath = ui->pathLineEdit->text();
    if (currentPath.isEmpty()) {
        QMessageBox::warning(this, tr("警告"), tr("请先选择要提取的项目文件夹"));
        return;
    }

    QFileInfo fileInfo(currentPath);
    if (!fileInfo.exists() || !fileInfo.isDir()) {
        QMessageBox::warning(this, tr("警告"), tr("所选路径不是有效的文件夹"));
        return;
    }

    QString saveFilePath = QFileDialog::getSaveFileName(this,
        tr("保存文件"), QString(),
        tr("Word文档 (*.docx)"));
        
    if (saveFilePath.isEmpty()) {
        return;
    }
    
    // 显示进度条并初始化
    ui->progressBar->show();
    ui->progressLabel->show();
    ui->progressLabel->setText(tr("正在统计文件数量..."));
    ui->progressBar->setValue(0);
    
    // 禁用提取按钮，防止重复点击
    ui->extractButton->setEnabled(false);
    
    // 设置参数并启动处理
    worker->setParameters(currentPath, getSelectedLanguages(), saveFilePath);
    QMetaObject::invokeMethod(worker, "process", Qt::QueuedConnection);
}

void ExtractPage::onLanguageSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
    Q_UNUSED(selected);
    Q_UNUSED(deselected);
    proxyModel->setSelectedLanguages(getSelectedLanguages());
} 